package com.samphanie.auiu.biz_detail.biz.goods

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.samphanie.auiu.LoginServiceProvider
import com.samphanie.auiu.biz_detail.R
import com.samphanie.auiu.biz_detail.databinding.ActivityGoodsDetailBinding
import com.samphanie.auiu.common.route.AuiuRoute
import com.samphanie.auiu.common.ui.component.BaseAppBVMActivity
import com.samphanie.auiu.common.ui.view.EmptyView
import com.samphanie.auiu.library.log.AuiuLog
import com.samphanie.auiu.pub_mod.model.GoodsDetailModel
import com.samphanie.auiu.pub_mod.model.GoodsModel
import com.samphanie.auiu.pub_mod.model.selectPrice
import com.samphanie.auiu.ui.item.AuiuAdapter
import com.samphanie.auiu.ui.item.AuiuDataItem

/**
 * @author ZSY
 */
@Route(path = "/goods/detail")
class GoodsDetailActivity : BaseAppBVMActivity<ActivityGoodsDetailBinding, GoodsDetailViewModel>() {

    @JvmField
    @Autowired
    var goodsId: String? = ""

    @JvmField
    @Autowired
    var goodsModel: GoodsModel? = null

    private var emptyView: EmptyView? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_goods_detail
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        AuiuRoute.inject(this)
        super.onCreate(savedInstanceState)

        AuiuLog.et("商品Id：${goodsId}")
        assert(goodsId!!.isNotBlank()) { "goodsId must not be null" }
    }

    override fun initialize(savedInstanceState: Bundle?) {
        initView()
        preBindData()
    }

    private fun preBindData() {
        if (goodsModel == null) return
        val adapter = binding.recyclerView.adapter as AuiuAdapter
        adapter.addItemAt(
            0, GoodsDetailHeaderItem(
                goodsModel!!.sliderImages,
                selectPrice(goodsModel!!.marketPrice, goodsModel!!.groupPrice),
                goodsModel!!.completedNumText,
                goodsModel!!.goodsName
            ), false
        )
    }

    private fun initView() {

        binding.actionBack.setOnClickListener {
            onBackPressed()
        }

        binding.recyclerView.layoutManager = GridLayoutManager(this, 2)
        binding.recyclerView.adapter = AuiuAdapter(this)
        binding.recyclerView.addOnScrollListener(TitleScrollListener(callback = {
            binding.titleBar.setBackgroundColor(it)
        }))

        viewModel.queryGoodsDetailData().observe(this, {
            if (it == null) {
                showEmptyUI(true)
            } else {
                bindData(it)
            }
        })
    }

    private fun bindData(model: GoodsDetailModel) {
        showEmptyUI(false)

        val adapter = binding.recyclerView.adapter as AuiuAdapter
        val dataItems = mutableListOf<AuiuDataItem<*, *>>()
        // 头部模块
        dataItems.add(
            GoodsDetailHeaderItem(
                model.sliderImages,
                selectPrice(model.marketPrice, model.groupPrice),
                model.completedNumText,
                model.goodsName
            )
        )

        // 评论item
        dataItems.add(GoodsCommentItem(model))
        // 店铺
        dataItems.add(ShopItem(model))
        // 商品描述
        dataItems.add(GoodsAttrItem(model))
        // 图库
        model.gallery?.forEach {
            dataItems.add(GoodsGalleryItem(it))
        }
        // 相似商品
        model.similarGoods?.let {
            dataItems.add(SimilarTitleItem())
            it.forEach {
                dataItems.add(GoodsItem(it, false))
            }
        }

        adapter.clearItems()
        adapter.addItems(dataItems, true)

        updateFavoriteActionFace(model.isFavorite)
        updateOrderActionFace(model)
    }

    @SuppressLint("SetTextI18n")
    private fun updateOrderActionFace(model: GoodsDetailModel) {
        binding.actionOrder.text = "${selectPrice(model.marketPrice, model.groupPrice)} \n立即购买"
    }

    private fun updateFavoriteActionFace(favorite: Boolean) {
        binding.actionFavorite.setOnClickListener {
            toggleFavorite()
        }
        binding.actionFavorite.setTextColor(ContextCompat.getColor(this, if (favorite) R.color.color_dd2 else R.color.color_999))
    }

    private fun toggleFavorite() {
        if (!LoginServiceProvider.isLogin()) {
            LoginServiceProvider.login(this) {
                if (it) {
                    toggleFavorite()
                }
            }
        } else {
            binding.actionFavorite.isClickable = false
            viewModel.toggleFavorite().observe(this) { success ->
                if (success != null) {
                    updateFavoriteActionFace(success)
                    val message = if (success) "收藏成功" else "取消收藏成功"
                    showToast(message)
                } else {
                    showToast("网络异常")
                }
                binding.actionFavorite.isClickable = true
            }
        }
    }

    override fun createViewModel(): GoodsDetailViewModel {
        AuiuLog.et("商品Id：${goodsId}")
        return GoodsDetailViewModel(goodsId)
    }

    override fun showEmptyUI(isShow: Boolean) {
        if (isShow) {
            if (emptyView == null) {
                emptyView = EmptyView(this)
                emptyView!!.setIcon(R.string.if_empty3)
                emptyView!!.setDesc(getString(R.string.list_empty_desc))
                emptyView!!.layoutParams = ConstraintLayout.LayoutParams(-1, 1)
                emptyView!!.setButton(getString(R.string.list_empty_action)) {
                    viewModel.queryGoodsDetailData()
                }

                binding.rootContainer.addView(emptyView)
            }

            binding.recyclerView.visibility = View.GONE
            emptyView!!.visibility = View.VISIBLE
        } else {
            binding.recyclerView.visibility = View.VISIBLE
            if(emptyView != null) {
                emptyView!!.visibility = View.GONE
            }
        }
    }
}